package br.com.nutriplus.dao;

import java.io.File;
import java.io.IOException;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

import br.com.nutriplus.util.Log;

public class DBAccess {

	public static DBAccess instance = null;

	public static DBAccess getInstance() {
		if (instance == null)
			instance = new DBAccess();
		return instance;
	}

	// ############ Constants ############
	private static final String DATABASEFOLDER = "database";
	private static final String DATABASEFILE = "nutridb.odb";

	// ############ Variables ############
	private static EntityManagerFactory emf = null;

	public static EntityManagerFactory getEmf() {
		if (emf == null)
			try {
				_startDatabase();
			} catch (IOException e) {
				Log.f(e);
			}
		return emf;
	}

	private static void _startDatabase() throws IOException {
		
		File databaseFolder = new File(DATABASEFOLDER);
		databaseFolder.mkdirs();
		File databaseFile = new File(DATABASEFOLDER + "/" + DATABASEFILE);
		databaseFile.createNewFile();
		Log.i("Iniciando o banco de dados em " + databaseFile.getAbsolutePath());
		emf = Persistence.createEntityManagerFactory(databaseFile
				.getAbsolutePath());
	}

	public static synchronized EntityManager getEntityManager() {
		return getEmf().createEntityManager();
	}

	public static synchronized void close() {
		if (getEmf() != null)
			getEmf().close();
	}

}
